const TOKEN_KEY = 'token'

export function getToken() {
  return localStorage.getItem(TOKEN_KEY)
}

export function setToken(token: string) {
  localStorage.setItem(TOKEN_KEY, token)
}

export function clearToken() {
  localStorage.removeItem(TOKEN_KEY)
}

export function getUserInfo() {
  return JSON.parse(localStorage.getItem('userInfo') || '{}')
}

export function setUserInfo(userInfo: any) {
  localStorage.setItem('userInfo', JSON.stringify(userInfo))
}

export function clearUserInfo() {
  localStorage.removeItem('userInfo')
}

const isDev = import.meta.env.DEV

export function toLogin() {
  clearToken()
  localStorage.removeItem('user')
  localStorage.removeItem('userStore')
  localStorage.removeItem('layoutStore')
  localStorage.removeItem('keepPageStore')

  const href = isDev
    ? `http://localhost:3000/#/login?returnUrl=${location.href}`
    : `${location.origin}/tomato/#/login?returnUrl=${location.href}`

  try {
    if (top?.location) {
      top.location.href = href
    }
    else {
      location.href = href
    }
  }
  catch (error) {
    location.href = href
  }
}
